# TODO use an id to find the first post ?
class Topic < ActiveRecord::Base
  attr_accessor :content
  attr_accessor :updated_by
  
  belongs_to :forum
  belongs_to :user
  belongs_to :replied_by_user, :foreign_key => 'replied_by', :class_name => 'User'
  has_many :posts, :order => 'posts.created_at ASC', :dependent => :destroy
  has_one :first_post, :order => 'posts.created_at ASC', :class_name => 'Post'
  
  validates_presence_of :forum_id
  validates_presence_of :user_id
  validates_presence_of :title
  validates_presence_of :content
  
  def before_create
    self.permalink = self.title.to_permalink if self.permalink.blank?
  end
  
  def after_create
    self.posts.create(:content => self.content, :user_id => self.user_id, :new_topic => true)
    self.forum.last_reply_id = self.posts[0].id
    self.forum.increment(:topics_count)
    self.forum.increment(:posts_count)
    self.forum.save
  end
  
  def after_update
    self.first_post.update_attributes(:content => self.content, :updated_by => self.updated_by) unless self.content.nil?
  end
  
  def to_param
    "#{id}-#{permalink}"
  end
  
  def content
    self.new_record? ? @content : @content ||= self.first_post.content
  end
  
  def hit!
    Topic.increment_counter(:hits, self.id)
  end
end
